package com.xhh.greymall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.xhh.common.constant.ProductConstant;
import com.xhh.common.to.SkuHasStockVO;
import com.xhh.common.to.SkuReductionTo;
import com.xhh.common.to.SpuBoundsTo;
import com.xhh.common.to.es.SkuEsModel;
import com.xhh.common.utils.R;
import com.xhh.greymall.product.entity.*;
import com.xhh.greymall.product.feign.CouponFeignService;
import com.xhh.greymall.product.feign.SearchFeignService;
import com.xhh.greymall.product.feign.WareFeignService;
import com.xhh.greymall.product.service.*;
import com.xhh.greymall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhh.common.utils.PageUtils;
import com.xhh.common.utils.Query;

import com.xhh.greymall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrService attrService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * // TODO 高级部分完善
     *  @GlobalTransactional
     * @param vo
     */
    //Seata AT 分布式事务
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVO vo) {
        // 1.保存Spu基本信息->pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveInfo(spuInfoEntity);

        // 2. 保存描述的信息->pms_spu_info_desc,！主键为spuid，不自增
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuDesc(spuInfoDescEntity);

        // 3. 保存图片集->pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveSpuImages(spuInfoEntity.getId(), images);

        // 4. 保存规格参数->pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        productAttrValueService.saveSpuBaseAttrs(spuInfoEntity.getId(), baseAttrs);

        // 5.保存spu的积分信息-> greymall_sms->sms_spu_bounds（跨数据库-使用openfeign）
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        Bounds bounds = vo.getBounds();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if(r.getCode() != 0){
            log.error("远程调用coupon积分信息失败");
        }

        // 6. 保存当前spu对应的所有sku信息
        List<Skus> skus = vo.getSkus();
        if(skus != null && skus.size() > 0){
                skus.forEach(skuInfo->{
                List<Images> img = skuInfo.getImages();
                String defaultImg = "";
                for (Images i : img) {
                    if(i.getDefaultImg() == 1){
                        defaultImg = i.getImgUrl();
                    }
                }

                SkuInfoEntity baseInfo = new SkuInfoEntity();
//            private String skuName;
//            private BigDecimal price;
//            private String skuTitle;
//            private String skuSubtitle;
                BeanUtils.copyProperties(skuInfo, baseInfo);
                baseInfo.setBrandId(vo.getBrandId());
                baseInfo.setCatalogId(vo.getCatalogId());
                baseInfo.setSpuId(spuInfoEntity.getId());
                baseInfo.setSkuDesc("");
                baseInfo.setSaleCount(0L);
                baseInfo.setSkuDefaultImg(defaultImg);
                // 6.1 sku的基本信息->pms_sku_info
                skuInfoService.save(baseInfo);

                Long skuId = baseInfo.getSkuId();

                List<SkuImagesEntity> skuImages = skuInfo.getImages().stream().map(item -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setDefaultImg(item.getDefaultImg());
                    skuImagesEntity.setImgUrl(item.getImgUrl());
                    return skuImagesEntity;
                }).filter(entity->{
                    // 过滤掉路径为空,返回true需要
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                // 6.2 sku,保存图片信息->pms_sku_images
                skuImagesService.saveBatch(skuImages);

                List<Attr> attr = skuInfo.getAttr();
                List<SkuSaleAttrValueEntity> saleInfo = attr.stream().map(item -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(item, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                // 6.3 sku,保存销售属性->pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(saleInfo);

                // 6.4 保存sku的优惠，满减等
                // ->greymall_sms->sms_sku_ladder、sms_sku_full_reduction、sms_member_price（跨数据库-使用openfeign）
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(skuInfo, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R result = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(result.getCode() != 0){
                        log.error("远程调用coupon sku的优惠，满减失败");
                    }
                }
            });
        }



    }

    @Transactional
    @Override
    public void saveInfo(SpuInfoEntity spuInfoEntity) {
        this.save(spuInfoEntity);
    }

    /**
     * status: 0
     * key:
     * brandId: 6
     * catelogId: 225
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and(w->{
                w.eq("id", key).or().like("spu_name", key);
            });
        }

        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) &&!"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id", catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        //1、查出当前spuId对应的所有sku信息，品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        // TODO 4、查询当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrlistforspu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);

        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());

        // TODO 1、发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            R r = wareFeignService.getSkuHasStock(skuIdList);
            //
            TypeReference<List<SkuHasStockVO>> typeReference = new TypeReference<List<SkuHasStockVO>>() {
            };
            stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVO::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}",e);
        }

        //2、封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);
            // skuPrice,skuImg
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            //hasStock,hostScore
            //设置库存信息
            if(finalStockMap == null){
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            // TODO 2、热度评分
            esModel.setHotScore(0L);

            // brandName,brandImg,catelogName
            // TODO 3、查询品牌和分类的信息
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(category.getName());

            // attrs->attrId,attrName,attrValue
            // 设置检索属性
            esModel.setAttrs(attrsList);

            return esModel;
        }).collect(Collectors.toList());

        // TODO 5、将数据发送给es进行保存 greymall-search；
        R r = searchFeignService.productStatusUp(upProducts);
        if(r.getCode() == 0 ){
            // 远程调用成功
            // TODO 6、修改当前spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getType());
        } else {
            // 远程调用失败
            // TODO 7、重复调用？接口幂等性，重试机制
            /**
             * Feign调用流程
             * 1、构造请求数据，将对象转为json
             *      SynchronousMethodHandler->RequestTemplate template = this.buildTemplateFromArgs.create(argv);
             * 2、发送请求进行执行
             *      SynchronousMethodHandler->executeAndDecode(template, options);
             * 3、执行请求会有重试机制
             *      Retryer retryer = this.retryer.clone();
             *      retryer.continueOrPropagate(e);
             *      while(true) {
             *             try {
             *                 return this.executeAndDecode(template, options);
             *             } catch (RetryableException var9) {
             *                 RetryableException e = var9;
             *
             *                 try {
             *                     retryer.continueOrPropagate(e);
             */

        }

    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        return getById(spuId);
    }

}